const { ipcMain } = require("electron");
const { sqlite } = require("../JDBC/init");
const windows = global.windows;
const pvf = require('./pvf');
const fs = require("fs");
const Path = require('path');
const { rmAndmkdir } = require('../Common')
const init = () => {

}

const initIpcMain = () => {
    let ipcMain = require("electron").ipcMain;

    //ipcMain不能传递带方法的对象，只能带着token相互发消息了
    ipcMain.on("pvf-pack", (event, channel, token, ...data) => {
        if (Pvf[channel]) {
            Pvf[channel](token, ...data);
        } else {
            console.error("错误的channel", channel)
        }
    })
}

const Pvf = {
    openPvfFile(token, path) {
        console.log("openPvfFile", token, path);

        //校验path
        if (!path || path == "") {
            return;
        }

        if (!fs.existsSync(path)) {
            return;
        }

        if (path.toLowerCase().indexOf(".pvf") == -1) {
            return;
        }

        const pvfName = Path.basename(path);
        const extName = Path.extname(path);
        const pvfPath = Path.dirname(path);
        const outDir = Path.join(pvfPath, pvfName.replace(extName, "")); //outdir

        //存入数据库
        sqlite.config.replaceInto("pvf", path);

        //删除解压后的文件夹
        rmAndmkdir(outDir);

        //调用pvf解压
        pvf.decomprFile(path, outDir).then(rs => {
            //遍历解压后的文件 存入数据库
            windows.main.webContents.send("pvf-pack-reply", "openPvfFile", token, null, true);
        }).catch(err => {
            windows.main.webContents.send("pvf-pack-reply", "openPvfFile", token, err, null);
        })
    },
}

init();
initIpcMain();

module.exports = Pvf